package com.ciei.dpagm.service;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ciei.dpagm.common.service.BaseService;
import com.ciei.dpagm.entity.Right;
import com.ciei.dpagm.entity.RoleRight;
import com.ciei.dpagm.mapper.RoleRightMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class RoleRightService extends BaseService<RoleRightMapper,RoleRight> {

    @Autowired
    private RightService rightService;

    // TODO - 待确认用途
	public JSONObject updateRoleRight(Integer roleId, String rightIs) {
		JSONObject json = new JSONObject();
		List<RoleRight> rights=findByProperty("roleId",roleId);
        List<String> idArr = new ArrayList<>(Arrays.asList(rightIs.split(",")));
        List<Integer> rightIdsToDelete = rights.stream()
                .filter(r -> !idArr.contains(r.getRightId().toString()))
                .map(RoleRight::getRightId)
                .collect(Collectors.toList());
        List<String> rightIdList = rights.stream().map(r -> r.getRightId().toString()).collect(Collectors.toList());
        idArr.removeAll(rightIdList);
        List<RoleRight> rightToAdd = new ArrayList<>();
        for (String id : idArr) {
            RoleRight roleRight = new RoleRight();
            Integer iid = Integer.valueOf(id);
            roleRight.setRightId(iid);
            roleRight.setRoleId(roleId);
            rightToAdd.add(roleRight);
        }
        insertBatchSomeColumn(rightToAdd);
        QueryWrapper<RoleRight> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(RoleRight::getRoleId, roleId)
                .in(RoleRight::getRightId, rightIdsToDelete);
        remove(wrapper);
		return json;
	}

    /**
     * 查询角色关联的所有权限
     * @param roleIds 角色ID集合
     * @return rightId集合
     */
    public Set<Integer> getRightIdSet(Collection<Integer> roleIds) {
        if (roleIds == null || roleIds.isEmpty()) {
            return new HashSet<>();
        }
        LambdaQueryWrapper<RoleRight> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(RoleRight::getRoleId, roleIds).select(RoleRight::getRightId);
        List<RoleRight> roleRightList = list(wrapper);
        if (roleRightList.isEmpty()) {
            return new HashSet<>();
        }
        return roleRightList.stream().map(RoleRight::getRightId).collect(Collectors.toSet());
    }

    /**
     * 获取角色拥有的权限ID
     * @param roleIds	角色ID列表
     * @param leafOnly  只返回叶子节点的ID
     * @return			权限ID集合
     */
    public Set<Integer> loadRightIdsByRoleId(List<Integer> roleIds, boolean leafOnly) {
        if (roleIds == null || roleIds.isEmpty()) {
            return new HashSet<>();
        }
        QueryWrapper<RoleRight> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(RoleRight::getRoleId, roleIds)
                .select(RoleRight::getRightId);
        List<RoleRight> roleRightList = list(queryWrapper);
        if (leafOnly) {
            List<Right> rightList = rightService.findListByIds(roleRightList.stream().map(RoleRight::getRightId).collect(Collectors.toSet()));
            Set<Integer> pids = rightList.stream().map(Right::getParentId).collect(Collectors.toSet());
            return rightList.stream().filter(r -> !pids.contains(r.getRightId())).map(Right::getRightId).collect(Collectors.toSet());
        } else {
            return roleRightList.stream().map(RoleRight::getRightId).collect(Collectors.toSet());
        }
    }

    /**
     * 获取角色拥有的权限ID
     * （只返回叶子节点，用于勾选权限树）
     * @param roleId	角色ID
     * @return			权限ID集合
     */
    public Set<Integer> loadRightIdsByRoleId(Integer roleId) {
        List<Integer> roleIdList = new ArrayList<>();
        roleIdList.add(roleId);
        return loadRightIdsByRoleId(roleIdList, false);
    }

    /**
     * 新增或更新[角色-权限关系]
     * @param roleId 角色ID
     * @param rightIds 该角色分配的权限ID
     * @return true 表示操作成功
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdate(Integer roleId, Collection<Integer> rightIds) {
        if (roleId == null) {
            return false;
        }
        delete(roleId);
        List<RoleRight> roleRightList = new ArrayList<>();
        if (rightIds != null && rightIds.size() > 0) {
            rightIds.forEach(rightId -> roleRightList.add(new RoleRight(roleId, rightId)));
        }
        if (roleRightList.size() > 0) {
            return insertBatch(roleRightList);
        }
        return true;
    }

    /**
     * 根据角色ID删除
     * @param roleId 角色ID
     * @return true 表示删除成功
     */
    public boolean delete(Integer roleId) {
        if (roleId == null) {
            return false;
        }
        LambdaQueryWrapper<RoleRight> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(RoleRight::getRoleId, roleId);
        return remove(queryWrapper);
    }

    /**
     * 根据权限ID集合批量删除
     * @param rightIdSet 要删除的权限ID集合关联数据
     * @return true 表示删除成功
     */
    public boolean delete(Set<Integer> rightIdSet){
        LambdaQueryWrapper<RoleRight> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(RoleRight::getRightId, rightIdSet);
        return remove(queryWrapper);
    }

}


